<?php

namespace App\Http\Controllers\ZHIHU\Topics;

use DB;
use Config;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use App\Http\Controllers\ZHIHU\ApiController;
use App\Http\Controllers\ZHIHU\Systems\SystemsConfigController as SCC;
use App\Validate\Zhihu\ZhihuValidator;
use App\Eloqumd\Zhihu\ZhihuQuestion;
use App\Eloqumd\Zhihu\ZhihuTopic;
use App\Eloqumd\Zhihu\ZhihuTopicQuestion;
use App\Eloqumd\Zhihu\ZhihuMessage;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuUserPrestige;
use App\Eloqumd\Zhihu\ZhihuPrestige;
use App\Jobs\SystemMessagePublishedNotify;

class TopicController extends ApiController
{
    // 发布问题
    public function publishQuestion(Request $request)
    {
        $param = $request->all();
        if (true !== $validateRes = ZhihuValidator::publishQuestion($param)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuQuestion;
            $model->user_id = $this->apiUser['id'];
            $model->title = $param['title'];
            $model->lead = $param['lead'] ?? '';
            $model->editor = $param['editor'] ?? 'editor';
            if ($model->editor == 'md') {
                $model->content = $param['editormd-html-code'];
                $model->editormd_html_code = $param['content'];
            } else {
                $model->content = $param['content'];
                $model->editormd_html_code = '';
            }
            $model->cates = $param['cates'];
            $model->status = 1;
            $model->topic_id = $param['topic_id'];
            $model->created_at = Carbon::now();
            $model->save();

            // 话题关联
            $topicQuestion = new ZhihuTopicQuestion;
            $topicQuestion->question_id = $model->id;
            $topicQuestion->topic_id = $param['topic_id'];
            $topicQuestion->created_at = Carbon::now();
            $topicQuestion->save();

            // 话题总数更新
            $topic = ZhihuTopic::find($param['topic_id']);
            $topic->questions_count = $topic->questions_count + 1;
            $topic->followers_count = $topic->followers_count + 1;
            $topic->updated_at = Carbon::now();
            $topic->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 编辑-设置问题
    public function configQuestion(Request $request)
    {
        $param = $request->all();
        if (true !== $validateRes = ZhihuValidator::configQuestion($param)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuQuestion::find($param['id']);
            $model->title = $param['title'];
            $model->lead = $param['lead'] ?? '';
            $editor = $param['editor'] ?? 'editor';
            $model->editor = $editor;
            if ($editor == 'md') {
                $model->content = $param['editormd-html-code'];
                $model->editormd_html_code = $param['content'];
            } else {
                $model->content = $param['content'];
                $model->editormd_html_code = '';
            }
            // $model->content = $param['content'];
            $model->updated_at = Carbon::now();
            $model->close_comment = (int)$param['close_comment'];
            // $model->is_hidden = (int)$param['is_hidden'];
            $model->is_guest_view = (int)$param['is_guest_view'];
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 查看问题
    public function viewQuestion(Request $request)
    {
        $questionId = $request->input('id', 0);
        if (!$questionId) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Parameter-Friend-No-Question'), null, 'verror');
        }

        $questionData = ZhihuQuestion::find($questionId);
        if (empty($questionData)) {
            return $this->jsonReturns(50000, trans('zhihu.Illegal-Parameter-Friend-No-Question'), null, 'verror');
        }

        $topicData = ZhihuTopic::find($questionData['topic_id']);

        $questionData['topic_name'] = $topicData['name'];
        $questionData['close_comment'] = (string)$questionData['close_comment'];
        $questionData['is_guest_view'] = (string)$questionData['is_guest_view'];

        if ($questionData['editor'] == 'md') {
            $html = $questionData['content'];
            $content = $questionData['editormd_html_code'];
            $questionData['content'] = $content;
            $questionData['editormd_html_code'] = $html;
        }

        return $this->jsonReturns(10000, $this->success, $questionData, 'get');
    }

    // 删除问题-个人及管理员
    public function removeQustion(Request $request)
    {
        $questionId = $request->input('id', 0);
        if (!$questionId) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Parameter-Friend-No-Question'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuQuestion::find($questionId);
            $model->status = 0;
            $model->removed_at = Carbon::now();
            $model->remove_reason = (!isset($param['remove_reason']) || empty($param['remove_reason']) ? (
                $this->apiUser['user_type'] == 0 ? trans('zhihu.The-Remove-Question-System') : trans('zhihu.The-Remove-Question-Personal')
            ) : $param['remove_reason']);
            $model->remove_type = ($this->apiUser['user_type'] == 0 ? 'system' : 'personal');
            $model->save();

            // 话题总数更新
            $topic = ZhihuTopic::find($model->topic_id);
            $topic->questions_count = $topic->questions_count - 1;
            $topic->followers_count = $topic->followers_count - 1;
            $topic->updated_at = Carbon::now();
            $topic->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'delete');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'delete');
        }
    }

    // 问题列表-个人及管理员-个人话题没有筛选条件
    public function listQuestion(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // key
        $key = $request->input('key', '');
        // 关键字
        $keyword = $request->input('keyword', '');
        // 话题类型
        $topic_id = $request->input('topic_id', '');
        // 是否删除
        $status = $request->input('status', 1);
        // 用户ID
        $userId = $request->input('user_id', 0);

        $where = null;
        // 快捷搜索-问题标题
        if ($keyword) {
            $where[] = ['title', 'like', "%{$keyword}%", 'OR'];
        }
        if ($topic_id) {
            $where[] = ['topic_id', '=', $topic_id, 'AND'];
        }
        // 用户类型过滤
        if ($userId) {
            $where[] = ['user_id', '=', $userId, 'AND'];
        } else {
            if ($this->apiUser['user_type'] != 0) {
                $where[] = ['user_id', '=', $this->apiUser['id'], 'AND'];
            }
        }
        // 分类过滤
        if ($key) {
            $where[] = ['cates', '=', $key, 'AND'];
        }
        $where[] = ['status', '=', $status, 'AND'];

        $totalCount = ZhihuQuestion::where($where)->count();
        $listData = ZhihuQuestion::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('is_cream', 'desc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $topic = ZhihuTopic::find($v['topic_id']);
            $user = ZhihuUser::find($v['user_id']);
            $listData[$k]['topic'] = $topic->name;
            $listData[$k]['publishname'] = $user->nickname;
            $listData[$k]['fclr'] = $v['favourite_count'] . ' / ' . $v['answers_count'] . ' / ' . $v['followers_count'] . ' / ' . $v['read_count'];
            $listData[$k]['catesShow'] = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['timeShow'] = time_trans($v['created_at']);
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount, 'has_more' => $offest + count($listData) < $totalCount ? 1 : 0];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 设置/取消精华
    public function configQuestionCream(Request $request)
    {
        $id = $request->input('id', '');
        $is_cream = $request->input('is_cream', 0);

        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuQuestion::find($id);
            $model->is_cream = $is_cream;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();
            // 获取精华设置分值
            $score = (int)ZhihuPrestige::where('preskey', 'cream')->where('status', 1)->value('score');

            // 消息通知
            $msg = new ZhihuMessage;
            $msg->from_id = $this->apiUser['id'];
            $msg->from_name = $this->apiUser['nickname'];
            $msg->to_id = $model->user_id;
            $content = $is_cream == 1 ?
                trans('zhihu.System-Set-Cream-Content', [
                    'title' => $model->title,
                    'cate' => Config::get('api.zhihu_question_type')[$model->cates],
                    'score' => $score
                ]) :
                trans('zhihu.System-Unset-Cream-Content', [
                    'title' => $model->title,
                    'cate' => Config::get('api.zhihu_question_type')[$model->cates]
                ]);
            $msg->content = $content;
            $msg->status = 0;
            $msg->is_system = 1;
            $msg->created_at = Carbon::now();
            $msg->save();

            // socket通知
            $title = $is_cream == 1 ? trans('zhihu.System-Set-Cream-Notify-Title') : trans('zhihu.System-Unset-Cream-Notify-Title');
            $job = (new SystemMessagePublishedNotify([
                'channelType' => 'cream',
                'message' => $msg->content,
                'title' => $title,
                'data' => $msg->toArray()
            ]));
            $this->dispatch($job);

            // 声望记录添加
            if ($is_cream == 1) {
                ZhihuUserPrestige::insert([
                    'user_id' => $model->user_id,
                    'title' => trans('zhihu.System-Question-Become-Cream-Title', [
                        'cate' => Config::get('api.zhihu_question_type')[$model->cates],
                        'title' => $model->title,
                    ]),
                    'conent' => trans('zhihu.System-Question-Set-Cream-Add-Score-Content', [
                        'title' => $model->title,
                        'cate' => Config::get('api.zhihu_question_type')[$model->cates],
                        'score' => $score,
                        'id' => $id
                    ]),
                    'types' => 0,
                    'score' => $score,
                    'created_at' => Carbon::now()
                ]);
            }
            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 获取最新，最受欢迎问题列表
    public function getShowQuestionLimitList(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $key = $request->input('key', '');
        $limit = Config::get('api.zhihu_latest_question_list');

        $where = null;
        if ($key) {
            $where['cates'] = strtolower($key);
        }

        $latest = ZhihuQuestion::where('user_id', $userId)
			->where('status', 1)
            ->where($where)
            ->offset(0)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();
        foreach ($latest as $k => $v) {
            $latest[$k]['timeshow'] = time_trans($v['created_at']);
        }
        $loves = ZhihuQuestion::where('user_id', $userId)
			->where('status', 1)
            ->where($where)
            ->offset(0)
            ->limit($limit)
            ->orderBy('favourite_count', 'desc')
            ->get()
            ->toArray();

        $jsonData = [
            'latest' => $latest,
            'loves' => $loves
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 脏问题列表-管理员操作
    public function listDirtyQuestion(Request $request)
    {
        // 系统默认配置脏词过滤
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $request->input('keyword', '');

        $where = null;
        // 如果存在手动查找-不匹配系统默认
        // 脏问题查找主要从标题及内容检索
        if ($keyword) {
            $where[] = ['title', 'like', "%{$keyword}%"];
            $where[] = ['content', 'like', "%{$keyword}%", 'OR'];
        } else {
            if (is_null($configVal = SCC::getting('dirty'))) {
                return $this->jsonReturns(10000, $this->success, [
                    'list' => [], 'count' => 0
                ]);
            }

            if ($dirtyName = $configVal['dirtyName']) {
                $dirtyArr = explode(',', $dirtyName);
                foreach ($dirtyArr as $dirtyKey => $dirtyVal) {
                    $where[] = ['title', 'like', "%{$dirtyVal}%", !$dirtyKey ? 'AND' : 'OR'];
                    $where[] = ['content', 'like', "%{$dirtyVal}%", 'OR'];
                }
            } else {
                return $this->jsonReturns(10000, $this->success, [
                    'list' => [], 'count' => 0
                ]);
            }
        }

        $totalCount = ZhihuQuestion::where($where)->where('status', 1)->count();
        $listData = ZhihuQuestion::where($where)
            ->where('status', 1)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $topic = ZhihuTopic::find($v['topic_id']);
            $user = ZhihuUser::find($v['user_id']);
            $listData[$k]['topic'] = $topic->name;
            $listData[$k]['publishname'] = $user->nickname;
            $listData[$k]['catesShow'] = Config::get('api.zhihu_question_type')[$v['cates']];
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 脏问题标记-邮件通知-站内信通知-统计
    public function removeDirtyQuestion(Request $request)
    {
        // 管理员可以进行标记后统一删除，也可逐个删除
        // 系统标记
        // 参数兼容数组和字符串
        $id = $request->input('id', '');
        if (!is_array($id)) {
            $id = explode(',', $id);
        }

        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            // 数据标记
            ZhihuQuestion::whereIn('id', $id)->update([
                'is_dirty' => 1,
                'status' => 0,
                'remove_type' => 'system',
                'remove_reason' => trans('zhihu.The-Remove-Question-System')
            ]);

            // 私信记录
            $questionData = ZhihuQuestion::whereIn('id', $id)->get()->toArray();

            $score = (int)ZhihuPrestige::where('preskey', 'dirty')->where('status', 1)->value('score');
            $messageData = [];
            foreach ($questionData as $key => $val) {
                $messageData[] = [
                    'from_id' => $this->apiUser['id'],
                    'from_name' => $this->apiUser['nickname'],
                    'from_name' => ($this->apiUser['nickname'] ? $this->apiUser['nickname'] : $this->apiUser['name']),
                    'to_id' => $val['user_id'],
                    'content' => trans('zhihu.The-Dirty-Question-Remove-By-System', [
                        'name' => $val['title'],
                        'score' => $score
                    ]),
                    'created_at' => Carbon::now(),
                    'is_system' => 1
                ];
            }
            ZhihuMessage::insert($messageData);

            DB::commit();
            // 通知
            foreach ($messageData as $k => $v) {
                ZhihuUserPrestige::insert([
                    'user_id' => $v['to_id'],
                    'title' => trans('zhihu.System-Question-Beset-Dirty-Title', [
                        'cate' => Config::get('api.zhihu_question_type')[$questionData[$k]['cates']],
                        'title' => $questionData[$k]['title'],
                    ]),
                    'conent' => trans('zhihu.System-Question-Set-Dirty-Add-Score-Content', [
                        'cate' => Config::get('api.zhihu_question_type')[$questionData[$k]['cates']],
                        'title' => $questionData[$k]['title'],
                        'score' => $score,
                        'id' => $questionData[$k]['id'],
                    ]),
                    'types' => 1,
                    'score' => $score,
                    'created_at' => Carbon::now()
                ]);

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'dirty',
                    'message' => $v['content'],
                    // 'title' => $title,
                    'data' => $v
                ]));
                $this->dispatch($job);
            }

            return $this->jsonReturns(10000, $this->success, null, 'delete');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'delete');
        }
    }

    // 话题列表
    public function listTopics(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $request->input('keyword', '');

        $where = null;
        // 快捷搜索-话题名称
        if ($keyword) {
            $where[] = ['name', 'like', "%{$keyword}%", 'OR'];
        }

        $totalCount = ZhihuTopic::where($where)->count();
        $listData = ZhihuTopic::where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 创建话题
    public function createTopic(Request $request)
    {
        $param = $request->all();
        if (true !== $validateRes = ZhihuValidator::createTopic($param)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuTopic;
            $model->name = $param['name'];
            // $model->status = $param['status'] ?? 1;
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 设置话题
    public function configTopic(Request $request)
    {
        $param = $request->all();
        if (true !== $validateRes = ZhihuValidator::configTopic($param)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuTopic::find($param['id']);
            $model->name = $param['name'];
            $model->status = $param['status'];
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 启用禁用话题
    public function statusTopic(Request $request)
    {
        $topicId = $request->input('id', 0);
        $status = $request->input('status', '');
        if (!$topicId) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Parameter-Friend-No-Topic'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuTopic::find($topicId);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'status');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'status');
        }
    }
}
